package br.com.trumah.dao.impl;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.trumah.dao.interfaces.DoacaoDAO;
import br.com.trumah.model.Doacao;
import br.com.trumah.utils.HibernateUtil;

public class DoacaoDAOImpl implements DoacaoDAO {

	
	private Session session = null;
	private Transaction t = null;		
	
	@Override
	public void salvar(Doacao doacao) {
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.save(doacao);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
	}

	@Override
	public Doacao obterDoacao(long id) {
		
		Doacao doacao = null;
		
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			doacao = (Doacao) session.load(Doacao.class, id);
			
		} catch (HibernateException ex) {
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return doacao;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Doacao> listar() {
		
		List<Doacao> lista = null;
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			lista = session.createQuery("from Doacao").list();
			t.commit();
			
		} catch (HibernateException ex) {
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return lista;
	}
	

	@Override
	public void remover(Doacao doacao) {

		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.delete(doacao);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
	}

	@Override
	public void atualizar(Doacao doacao) {
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.update(doacao);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
	}

}
